<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1" import="Connect.*" %>

<%@ page import="java.io.*,java.util.*, javax.servlet.*"%>
<%@ page import="javax.servlet.http.*"%>
<%@ page import="org.apache.commons.fileupload.*"%>
<%@ page import="org.apache.commons.fileupload.disk.*"%>
<%@ page import="org.apache.commons.fileupload.servlet.*"%>
<%@ page import="org.apache.commons.io.output.*"%>
<%
	//////////////////////////////////////////// Extract input submitted by form input ///////////////////////////////////////////////////////////////
	// Text input variables.
	String id = "";
	String name = "";
	String year = "";
	String type = "";
	String description = "";
	String copies_sold = "";
	String copies_available = "";

	// Store the location to write the file and the submitted file.
	File file = null;
	FileItem input = null;

	int maxFileSize = 5000 * 1024;
	int maxMemSize = 5000 * 1024;
	ServletContext context = pageContext.getServletContext();
	//String filePath = context.getInitParameter("file-upload");//-------------------------------------------------
	String filePath = application.getRealPath("item_images") + "\\";

	// Verify the content type
	String contentType = request.getContentType();
	if ((contentType.indexOf("multipart/form-data") >= 0)) {

		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(maxMemSize);
		// Location to save data that is larger than maxMemSize.
		//factory.setRepository(new File("c:\\temp"));//----------------------------------------------------------
		factory.setRepository(new File(filePath));

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum file size to be uploaded.
		upload.setSizeMax(maxFileSize);
		try {
			// Parse the request to get file items.
			@SuppressWarnings("unchecked")
			List<FileItem> fileItems = upload.parseRequest(request);

			// Process the uploaded file items
			Iterator<FileItem> i = fileItems.iterator();

			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (!fi.isFormField()) {
					// Get the uploaded file parameters
					String fieldName = fi.getFieldName();
					String fileName = fi.getName();
					boolean isInMemory = fi.isInMemory();
					long sizeInBytes = fi.getSize();
					// Write the file
					if (fileName.lastIndexOf("\\") >= 0) {
						file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
					} else {
						file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
					}
					//fi.write(file);
					input = fi; // Store the submitted file. Do not write until the text components have been validated.
				} else {
					// FileItem is a form field.
					String value = fi.getString();
					if (fi.getFieldName().equalsIgnoreCase("name")) {
						name = value;
					} else if (fi.getFieldName().equalsIgnoreCase("year")) {
						year = value;
					} else if (fi.getFieldName().equalsIgnoreCase("type")) {
						type = value;
					} else if (fi.getFieldName().equalsIgnoreCase("description")) {
						description = value;
					} else if (fi.getFieldName().equalsIgnoreCase("copies_sold")) {
						copies_sold = value;
					} else if (fi.getFieldName().equalsIgnoreCase("copies_available")) {
						copies_available = value;
					} else if (fi.getFieldName().equalsIgnoreCase("id")) {
						id = value;
					}
				}
			}
			out.println("</body>");
			out.println("</html>");
		} catch (Exception ex) {
			out.println(ex);
			ex.printStackTrace();
		}
	}

	/////////////////////////////////////////////////////// Validate input ///////////////////////////////////////////////////////////////////////////
	// No name tests yet.
	boolean name_test = true;
	// Test if year is a non negative four digit number.
	boolean year_test = year.length() == 4;
	try {
		int num = Integer.parseInt(year);
		if (num < 0) {
			year_test = false;
		}
	} catch (Exception e) {
		year_test = false;
	}
	// No type tests yet.
	boolean type_test = true;
	// No description tests yet.
	boolean description_test = true;
	// Test if uploaded file is an image.
	boolean picture_test = true;
	String file_type = file.getName().substring(file.getName().lastIndexOf(".") + 1);
	if (!file_type.equalsIgnoreCase("gif") && !file_type.equalsIgnoreCase("jpg") && !file_type.equalsIgnoreCase("jpeg")
			&& !file_type.equalsIgnoreCase("png")) {
		picture_test = false;
	}
	boolean copies_sold_test = true;
	try {
		int num = Integer.parseInt(copies_sold);
		if (num < 0) {
			copies_sold_test = false;
		}
	} catch (Exception e) {
		copies_sold_test = false;
	}
	boolean copies_available_test = true;
	try {
		int num = Integer.parseInt(copies_available);
		if (num < 0) {
			copies_available_test = false;
		}
	} catch (Exception e) {
		copies_available_test = false;
	}
	boolean no_image = false;
	if (file.getName().equalsIgnoreCase("item_images")) {
		picture_test = true;
		no_image = true;
	}

	// Compile the error messages together.
	String errors = "";
	if (!name_test) {
		errors += "<br />";
	}
	if (!year_test) {
		errors += "* Year must be a non-negative 4 digit integer.<br />";
	}
	if (!type_test) {
		errors += "<br />";
	}
	if (!description_test) {
		errors += "<br />";
	}
	if (!copies_sold_test) {
		errors += "* Copes sold must be a non-negative integer.<br />";
	}
	if (!copies_available_test) {
		errors += "* Copes available must be a non-negative integer.<br />";
	}
	if (!picture_test) {
		errors += "* The picture must be a GIF, JPG, or PNG file.<br />";
	}

	// If there are any errors abort registration and send the user back to the
	// register page. It also saves non-password type data that the user has submitted.
	if (!errors.equals("")) {
		session.setAttribute("register_errors", errors);
		session.setAttribute("id", id);
		session.setAttribute("name", name);
		session.setAttribute("year", year);
		session.setAttribute("type", type);
		session.setAttribute("copies_sold", copies_sold);
		session.setAttribute("copies_available", copies_available);
		session.setAttribute("description", description);
		response.sendRedirect("edit_item.jsp");
	} else {
		// Getting information and updating the database.
		java.sql.Connection conn = null;
		try {
			// Connect to the database.
			Class.forName(ConnectionInfo.myJDBCDriver()).newInstance();
			java.util.Properties sysprops = System.getProperties();
			sysprops.put("user", ConnectionInfo.myUserID());
			sysprops.put("password", ConnectionInfo.myPassword());
			conn = java.sql.DriverManager.getConnection(ConnectionInfo.myURL(), sysprops);

			// Perform update query.
			name = "'" + name + "'";
			year = "'" + year + "'";
			type = "'" + type + "'";
			id = "'" + id + "'";
			copies_available = "'" + copies_available + "'";
			copies_sold = "'" + copies_sold + "'";
			description = "'" + description + "'";
			java.sql.Statement statement = conn.createStatement();
			statement.executeUpdate("UPDATE items SET name = " + name + " , year = " + year + " , type = " + type + " , description = "
					+ description + " , copies_sold = " + copies_sold + " , copies_available = " + copies_available + " WHERE id = " + id);

			// Copy the image onto the server if an image was submitted.
			if (!no_image) {
				file = new File(file.getParent() + "\\" + id.substring(1, id.length() -1) + ".png"); // all file types are considered PNG
				input.write(file);
			}

			// Redirect the user after adding theitem. Clear the form_type variable.
			out.println("Item updated! You will be redirected in 5 seconds.<br />");
			out.println("<a href=\"view_items.jsp\">Click here if you can't wait!</a>");
			response.setHeader("Refresh", "5; view_items.jsp");
		} catch (Exception e) {
			e.printStackTrace();
			out.print(e.toString());
		} finally {
			try {
				conn.close();
			} catch (Exception ee) {
			}
		}
	}
%>